package com.hx.vending.resolvers;


import com.hx.vending.annotation.CurrentAccountId;
import com.hx.vending.bean.config.Constants;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * @Description: 增加方法注入，将含有CurrentUser注解的方法参数注入当前userId
 * @See: com.hx.vending.resolvers.CurrentFieldIdMethodArgumentResolver
 */
@Component
public class CurrentAccountIdMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().isAssignableFrom(Integer.class) &&
                methodParameter.hasParameterAnnotation(CurrentAccountId.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Object AccountId =  nativeWebRequest.getAttribute(Constants.CURRENT_ACCOUNT_ID, RequestAttributes.SCOPE_REQUEST);
        String a = AccountId.toString();
        Integer currentAccountId = Integer.parseInt(a);
        if (null != currentAccountId) {
            return currentAccountId;
        }
        throw new MissingServletRequestPartException(Constants.CURRENT_FIELD_ID);
    }
}
